package com.bnyy.medicalHousekeeper.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.bnyy.common.Constant;
import com.bnyy.common.bean.UserInfo;
import com.bnyy.gbp.customsView.ScaleImageView;
import com.bnyy.medicalHousekeeper.GlideHelper;
import com.bnyy.medicalHousekeeper.PopupWindowHelper;
import com.bnyy.medicalHousekeeper.R;
import com.bnyy.medicalHousekeeper.base.BaseActivityImpl;
import com.bnyy.medicalHousekeeper.bean.Article;
import com.bnyy.medicalHousekeeper.bean.ArticleDetail;
import com.bnyy.medicalHousekeeper.bean.Goods;
import com.bnyy.medicalHousekeeper.fragment.HtmlArticleFragment;
import com.bnyy.medicalHousekeeper.fragment.ImageArticleFragment;
import com.bnyy.medicalHousekeeper.moudle.message.activity.Share2ContactsActivity;
import com.bnyy.medicalHousekeeper.request.BaseObserverImpl;
import com.bnyy.medicalHousekeeper.request.RequestManager;
import com.bnyy.medicalHousekeeper.wxapi.WXManager;
import com.bnyy.message.bean.chat.message_data.ArticleMessage;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;
import top.zibin.luban.OnRenameListener;

/**
 * Author : 关炳鹏
 * Description :
 * Date : 2023/2/7
 **/
public class ArticleDetailActivity extends BaseActivityImpl {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.fl_container)
    FrameLayout flContainer;
    @BindView(R.id.iv_goods)
    ScaleImageView ivGoods;
    @BindView(R.id.tv_goods_name)
    TextView tvGoodsName;
    @BindView(R.id.ll_goods)
    LinearLayout llGoods;

    private ArticleDetail articleDetail;

    public static void showByArticleId(Context context, Article article) {
        Intent intent = new Intent(context, ArticleDetailActivity.class);
        if (article.getArticle_id() == 0) {
            article.setArticle_id(article.getId());
        }
        article.setShareId(0);
        intent.putExtra("article", article);
        context.startActivity(intent);
    }

    public static void showByShareId(Context context, Article article) {
        Intent intent = new Intent(context, ArticleDetailActivity.class);
        intent.putExtra("article", article);
        context.startActivity(intent);
    }

    /**
     * @param context
     * @param article
     * @param goodsId 带商品的则文章详情不显示商品
     */
    public static void showGoodsArticle(Context context, Article article, int goodsId) {
        article.setShareId(0);
        Intent intent = new Intent(context, ArticleDetailActivity.class);
        intent.putExtra("article", article);
        intent.putExtra("goodsId", goodsId);
        context.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_article_detail;
    }

    @Override
    public String getTitleStr() {
        return "图文详情";
    }

    @Override
    public boolean unuseRefreshLayout() {
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Article article = (Article) getIntent().getSerializableExtra("article");

        if (article != null) {
            tvTitle.setText(article.getArticle_title());

            int goodsId = getIntent().getIntExtra("goodsId", -1);
            int articleId = article.getArticle_id();
            int shareId = article.getShareId();
            if (goodsId == -1) {
                llGoods.setVisibility(View.VISIBLE);
            }

            HashMap<String, Object> params = new HashMap<>();
            if (article.getShareId() != 0) {
                params.put("id", shareId);
            } else {
                params.put("id", articleId);
            }
            requestManager.request(requestManager.mJavaRetrofitService.getArticleDetail(RequestManager.getJsonRequestBody(params)),
                    new BaseObserverImpl<ArticleDetail>(mContext) {
                        @Override
                        public void onSuccess(ArticleDetail articleDetail) {
                            super.onSuccess(articleDetail);

                            ArticleDetailActivity.this.articleDetail = articleDetail;

                            Goods goods = articleDetail.getGoods();
                            if (goods != null) {

                                tvGoodsName.setText(goods.getGoods_name());
                                GlideHelper.setRoundImage(mContext, goods.getGoods_image(), ivGoods);

                                llGoods.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        switch (goods.getType()) {
                                            case 1:
                                                NormalGoodsDetailActivity.show(mContext, goods);
                                                break;
                                            case 2:
                                            case 3:
                                                ServiceGoodsDetailActivity.show(mContext, goods.getGoods_id());
                                                break;
                                        }
                                    }
                                });
                            }

                            Fragment fragment = null;
                            switch (articleDetail.getType()) {
                                case 1:
                                    fragment = ImageArticleFragment.getInstance(articleDetail);
                                    break;
                                case 2:
                                    fragment = HtmlArticleFragment.getInstance(articleDetail.getShare_url());
                                    break;
                            }
                            if (fragment != null) {
                                getSupportFragmentManager()
                                        .beginTransaction()
                                        .add(flContainer.getId(), fragment)
                                        .commitNowAllowingStateLoss();
                            }

                            TextView tvShare = new TextView(mContext);
                            tvShare.setBackgroundResource(R.mipmap.icon_share_black);
                            tvShare.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    View view = inflater.inflate(R.layout.pop_win_message_share_article, null);

                                    PopupWindow popupWindow = PopupWindowHelper.getInstance(mContext).show(view);

                                    view.findViewById(R.id.tv_wechat).setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            switch (articleDetail.getType()) {
                                                case 1:
                                                    compressionImages.clear();
                                                    mergeImage(SendMessageToWX.Req.WXSceneSession);
                                                    break;
                                                case 2:
                                                    shareUrl(SendMessageToWX.Req.WXSceneSession);
                                                    break;
                                            }
                                            popupWindow.dismiss();
                                        }
                                    });
                                    view.findViewById(R.id.tv_pyq).setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            switch (articleDetail.getType()) {
                                                case 1:
                                                    compressionImages.clear();
                                                    mergeImage(SendMessageToWX.Req.WXSceneTimeline);
                                                    break;
                                                case 2:
                                                    shareUrl(SendMessageToWX.Req.WXSceneTimeline);
                                                    break;
                                            }
                                            popupWindow.dismiss();
                                        }
                                    });
                                    view.findViewById(R.id.tv_chat).setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            ArticleMessage articleMessage = new ArticleMessage();
                                            UserInfo author = articleDetail.getAuthor();
                                            articleMessage.setAuthorImage(userInfoManager.getLoginUserInfo().getUserimg());
                                            articleMessage.setAuthorName(userInfoManager.getLoginUserInfo().getUsername());
                                            articleMessage.setId(articleId);
                                            articleMessage.setType(articleDetail.getType());
                                            articleMessage.setTitle(article.getArticle_title());
                                            articleMessage.setCoverImage(article.getArticle_image());
                                            Share2ContactsActivity.show(mContext, articleMessage);
                                            popupWindow.dismiss();
                                        }
                                    });
                                }
                            });
                            setOptions(tvShare);
                        }
                    });
        }
    }

    private ArrayList<String> compressionImages = new ArrayList<>();
    private File parent;

    private void mergeImage(int scene) {
        if (parent == null) {
            parent = new File(mContext.getExternalCacheDir(), "/image");
            if (!parent.exists()) {
                parent.mkdir();
            }
        }

        File articleImage = new File(parent, "article_" + articleDetail.getId() + ".png");

        if (articleImage.exists()) {
            WXManager.shareImage(mContext, articleImage, scene);
        } else {
            ArrayList<String> images = articleDetail.getText_images();
            if (compressionImages.size() == images.size()) {

                String downloadUrl = articleDetail.getDownload_url();
                File footerImage = new File(parent, downloadUrl.hashCode() + ".png");
                if (!footerImage.exists()) {
                    View footer = inflater.inflate(R.layout.item_image_article_footer, null);
                    Bitmap bitmapQrcode = QRCodeEncoder.syncEncodeQRCode(downloadUrl, ScreenUtils.getScreenWidth() / 5);
                    ImageView ivQrcode = footer.findViewById(R.id.iv_qr_code);
                    ivQrcode.setImageBitmap(bitmapQrcode);

                    Bitmap bitmapFooter = ImageUtils.view2Bitmap(footer);
                    ImageUtils.save(bitmapFooter, footerImage.getAbsolutePath(), Bitmap.CompressFormat.PNG);
                }
                compressionImages.add(footerImage.getAbsolutePath());

                int totalHeight = 0;
                int screenWidth = ScreenUtils.getScreenWidth();

                for (String path : compressionImages) {
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    //只请求图片宽高，不解析图片像素(请求图片属性但不申请内存，解析bitmap对象，该对象不占内存)
                    options.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(path, options);

                    totalHeight += screenWidth * options.outHeight / options.outWidth;
                }

                Bitmap result = Bitmap.createBitmap(ScreenUtils.getScreenWidth(), totalHeight, Bitmap.Config.ARGB_8888);
                Canvas canvas = new Canvas(result);

                int y = 0;
                for (String path : compressionImages) {
                    Bitmap bitmap = BitmapFactory.decodeFile(path);
                    int width = bitmap.getWidth();
                    int height = bitmap.getHeight();

                    float h = (float) screenWidth * height / width;

                    Matrix matrix = new Matrix();
                    matrix.postScale((float) screenWidth / width, h / height);

                    Bitmap target = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
                    canvas.drawBitmap(target, 0, y, null);

                    bitmap.recycle();
                    target.recycle();
                    y += h;
                }

                ImageUtils.save(result, articleImage, Bitmap.CompressFormat.PNG);

                WXManager.shareImage(mContext, articleImage, scene);

            } else {
                String url = images.get(compressionImages.size());
                String[] split = url.split("/");
                String fileName = split[split.length - 1];

                File compressionImage = new File(parent, fileName);
                if (compressionImage.exists()) {
                    compressionImages.add(compressionImage.getAbsolutePath());
                    mergeImage(scene);
                } else {
                    File originalImage = new File(parent, "original-" + fileName);
                    if (originalImage.exists()) {
                        compress(originalImage, compressionImage, scene);
                    } else {
                        Glide.with(mContext)
                                .load(url)
                                .into(new CustomTarget<Drawable>() {
                                    @Override
                                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {

                                        Bitmap bitmap = ImageUtils.drawable2Bitmap(resource);
                                        ImageUtils.save(bitmap, originalImage, Bitmap.CompressFormat.PNG);
                                        bitmap.recycle();

                                        compress(originalImage, compressionImage, scene);
                                    }

                                    @Override
                                    public void onLoadCleared(@Nullable Drawable placeholder) {

                                    }
                                });
                    }
                }
            }
        }
    }

    private void compress(File originalImage, File compressionImage, int scene) {
        Luban.with(mContext)
                .load(originalImage)
                .setTargetDir(compressionImage.getParent())
                .ignoreBy(100)
                .setFocusAlpha(true)
                .setRenameListener(new OnRenameListener() {
                    @Override
                    public String rename(String filePath) {
                        return compressionImage.getName();
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(File file) {
                        compressionImages.add(file.getAbsolutePath());

                        mergeImage(scene);
                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                })
                .launch();
    }

    public void shareUrl(int scene) {
//        articleDetail.setArticle_image("https://t7.baidu.com/it/u=2405382010,1555992666&fm=193&f=GIF");
//        articleDetail.setArticle_image("http://47.106.134.247/serve/orders/d679817a-c2d9-11ed-957a-0242ac140008.jpeg"); // 180kb
//        articleDetail.setArticle_image("http://47.106.134.247/serve/orders/d66f5736-c2d9-11ed-b3cf-0242ac140008.jpg"); // 531kb
        Glide.with(mContext)
                .load(articleDetail.getArticle_image())
//                .override(50, 50)
                .into(new CustomTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {

                        IWXAPI api = WXAPIFactory.createWXAPI(mContext, Constant.WX.APP_ID);
                        //初始化一个WXWebpageObject，填写url
                        WXWebpageObject webpage = new WXWebpageObject();
                        webpage.webpageUrl = articleDetail.getShare_url();

                        //用 WXWebpageObject 对象初始化一个 WXMediaMessage 对象
                        WXMediaMessage msg = new WXMediaMessage(webpage);
                        msg.title = articleDetail.getArticle_title();
                        msg.description = "";

                        Bitmap bitmap = ImageUtils.drawable2Bitmap(resource);

                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
                        int options = 90;
                        while (baos.toByteArray().length / 1024 > 25) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
                            baos.reset(); // 重置baos即清空baos
                            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
                            options -= 10;// 每次都减少10
                        }

                        msg.thumbData = baos.toByteArray();

                        //构造一个Req
                        SendMessageToWX.Req req = new SendMessageToWX.Req();
                        req.transaction = "webpage_" + System.currentTimeMillis();
                        req.message = msg;
                        req.scene = scene;

                        //调用api接口，发送数据到微信
                        api.sendReq(req);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {

                    }
                });
    }

    public static Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 90;
        while (baos.toByteArray().length / 1024 > 30) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset(); // 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }
}
































